import { joinTime, transformUser } from './helper'
import { uuid } from '@/utils'
import { PAGE_SIZES } from '@/constant/modules/paging'
import type { ShiftUnit, TableColumn } from '@/types'

import { schedulingApi } from '@/api'

function getShiftUnitLists(params: {
  pageNumber: number
  pageSize: number
}) {
  const { pageNumber = 1, pageSize = 10 } = params || {}
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve([
        ...Array(pageSize)
          .fill(1)
          .map((_v, i) => {
            const id = (pageNumber - 1) * pageSize + i + 1
            const rand = () =>
              +Math.random().toString().slice(2)
            return {
              id,
              name: `班次单元名称${id}`,
              details: [
                {
                  id: rand(),
                  name: `早班${rand()}`,
                  time: '06:00 - 14:00',
                  duration: 8 * 60,
                },
                {
                  id: rand(),
                  name: `晚班${rand()}`,
                  time: '14:00 - 22:00',
                  duration: 8 * 60,
                },
                {
                  id: rand(),
                  name: `通班${rand()}`,
                  time: '22:00 - 06:00',
                  duration: 8 * 60,
                },
              ],
            }
          }),
      ])
    }, 1e3)
  })
}

function transfer(
  data: {
    shiftList: any[]
    shiftUnit: any
  }[],
): ShiftUnit[] {
  return data.map(({ shiftList: m, shiftUnit: n }) => ({
    id: n.id,
    name: n.name,
    details: (m || []).map(v => ({
      id: v.id,
      name: v.name,
      time: joinTime(v.startTime, v.endTime),
      duration: v.totalTimeMinute,
      durationString: convertMinutesToHoursAndMinutes(
        v.totalTimeMinute,
        true,
      ) as string,
      isCrossDay: v.overnightShift,
    })),
    ...transformUser(n),
  }))
}

/** 分钟数转时分 */
export function convertMinutesToHoursAndMinutes(
  totalMinutes: number,
  format?: boolean,
) {
  const hours = Math.floor(totalMinutes / 60)
  const minutes = totalMinutes % 60

  const h = hours.toString().padStart(2, '0')
  const m = minutes.toString().padStart(2, '0')

  return format
    ? `${h}时${m}分`
    : {
        hours: h,
        minutes: m,
      }
}

export function useShiftUnitLists() {
  const [loading, setLoading] = useState(true)
  const pagination = reactive({
    pageNumber: 1,
    pageSize: PAGE_SIZES[0]!,
    total: 0,
  })
  const columns: TableColumn<ShiftUnit>[] = reactive([
    { key: uuid(), label: '班次单元名称', prop: 'name' },
  ])
  const [lists, setLists] = useShallowState<ShiftUnit[]>(
    [],
  )

  async function getLists(name?: string) {
    setLoading(true)
    try {
      const { data }
        = await schedulingApi.selectShiftUnitList({
          name: name ?? '',
        })
      setLists(transfer(data || []))
    }
    catch (e) {
    }
    finally {
      setLoading(false)
    }
  }

  return {
    loading,
    pagination,
    columns,
    lists,
    setLists,
    getLists,
  }
}
